<?php
namespace service;
use Alipay\AopClient;
use Alipay\Request\AlipayTradeAppPayRequest;
use Alipay\Request\AlipayTradeQueryRequest;
use think\facade\Config;

class Alipay {
    private static $client = null;
    protected $result = null;
    public function __construct($public_path=null,$private_path=null){
        $public_path = $public_path??'../data/alipay_cert/private_key.pem';
        $private_path = $private_path??'../data/alipay_cert/public_key.pem';
        $keyPair = \Alipay\Key\AlipayKeyPair::create(
            file_get_contents($public_path),
            file_get_contents($private_path)
        );
        self::$client = new AopClient(Config::get('alipay.app_id'),$keyPair);
        self::$client->apiVersion = '1.0';
        self::$client->signType = 'RSA2';
        self::$client->postCharset='utf-8';
        self::$client->format='json';
    }

    /**
     * @param string $out_trade_no
     * @param string $total_amount
     * @param string $subject
     * @param string $timeout_express
     * @param string $body
     * @return string
     */
    public function app($out_trade_no='',$total_amount='',$subject='',$timeout_express='',$body=''){
        $order = [
            'out_trade_no'=>$out_trade_no,
            'total_amount'=>$total_amount,
            'subject'=>$subject,
            'body'=>$body?:$subject,
            'timeout_express'=> $timeout_express?:'90m',
        ];
        $request = new AlipayTradeAppPayRequest();
        $request->setNotifyUrl(Config::get('alipay.notify_url'));
        $request->setBizContent(\GuzzleHttp\json_encode($order));
        $result = self::$client->sdkExecute($request);
        return $result;
    }

    /**
     * 查询订单
     * @param $out_trade_no
     * @param string $trade_no
     * @return $this
     */
    public function find($out_trade_no,$trade_no=''){
        $request = new AlipayTradeQueryRequest();
        $biz = [
            'out_trade_no'=>$out_trade_no,
            'trade_no'=>$trade_no
        ];
        $request->setBizContent(\GuzzleHttp\json_encode($biz));
        $this->result = $this->reset($request,self::$client->execute($request));
        return $this;
    }

    /**
     * @return null
     */
    public function getResult(){
        return $this->result;
    }

    /**
     * @param $request
     * @param $result
     * @return string
     */
    private function reset($request,$result){
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        return \GuzzleHttp\json_encode(\GuzzleHttp\json_encode($result->$responseNode),true);
    }
}